﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Lesson7_code2 : MonoBehaviour
{
    public Transform target;
    //当一个物体B在物体A左前方20度角或右前方30度范围内，并且离A只有5米距离时，在控制台打印“发现入侵者”
    void Update()
    {
        Debug.DrawRay(this.transform.position, this.transform.forward, Color.red);
        Debug.DrawRay(this.transform.position, target.position - this.transform.position, Color.red);

        float distance = Vector3.Distance(this.transform.position, target.transform.position);
        if (distance <= 5)
        {
            //判断左右
            Vector3 c1 = Vector3.Cross(this.transform.position, target.position);
            //判断前后
            if (Vector3.Dot(this.transform.forward, target.position - this.transform.position) > 0)
            {
                float angle = Vector3.Angle(this.transform.forward, target.position - this.transform.position);
                if (c1.y >= 0 && angle <= 30)
                {
                    Debug.LogFormat("右前方发现入侵者...");
                }
                else if (angle <= 20)
                {
                    Debug.LogFormat("左前方发现入侵者...");
                }
            }
        }
    }
}
